# -*- coding: utf-8 -*-
# Author: ideaPeng
#
# Check Status Module

import os
import time
import socket
import struct
import traceback
import requests
import json

EXPIRE_TIME = 1800

def get_token():
    corp_id = 'ww8297ab611e182c45'
    corp_secret = 'uQ-xdANz_73DPG3PJ1Tu4jmSootoyaI6ZVrnfdv0-IE'
    url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
    values = {'corpid': corp_id, 'corpsecret': corp_secret}

    try:
        fname = './token.conf'
        if os.path.exists(fname):
            fp = open(fname, 'r')
            confs = fp.read().replace('\n', '').split(',')
            last_time = float(confs[0])
            token = confs[1]
            fp.close()

            cur_time = time.time()
            if cur_time - last_time > 0 and cur_time - last_time < EXPIRE_TIME:
                return token
            else:
                fp = open(fname, 'w')
                req = requests.post(url, params = values)
                data = json.loads(req.text)
                new_token = data['access_token']
                content = '%s,%s' % (str(cur_time), new_token)
                fp.write(content)
                fp.close()

                return new_token
        else:
            print('write new')
            cur_time = time.time()
            fp = open(fname, 'w')
            req = requests.post(url, params = values)
            data = json.loads(req.text)
            new_token = data['access_token']
            content = '%s,%s' % (str(cur_time), new_token)
            fp.write(content)
            fp.close()

            return new_token
    except Exception as e:
        print('ERROR: can not get token')
        traceback.print_exc()
        os.remove('./token.conf')
        
        
def send_msg(message,userlist="YouXiongKai"):
#     user_list = 'YouXiongKai'
    # user_list = 'YouXiongKai'
    # user_list = 'YouXiongKai|YunShaoNianTaiMeiHao|porunacabeza|jinnil|fan'
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s' % (get_token())
    agent_id = '1000002'

    send_values = {
        'touser': userlist,
        'msgtype': 'text',
        'agentid': agent_id,
        'text':{
            'content': message
        },
        'safe': '0'
    }
    send_msgs = (bytes(json.dumps(send_values), 'utf-8'))
    res = requests.post(send_url, send_msgs).json()
    return res

# def send_msg(message):
# #     user_list = 'YouXiongKai'
#     user_list = 'YouXiongKai'
#     # user_list = 'YouXiongKai|YunShaoNianTaiMeiHao|porunacabeza|jinnil|fan'
#     send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s' % (get_token())
#     agent_id = '1000002'

#     send_values = {
#         'touser': user_list,
#         'msgtype': 'text',
#         'agentid': agent_id,
#         'text':{
#             'content': message
#         },
#         'safe': '0'
#     }

#     send_msgs = (bytes(json.dumps(send_values), 'utf-8'))
#     res = requests.post(send_url, send_msgs).json()

def send_markdown(msg,userlist='YouXiongKai'):
#     user_list = 'YouXiongKai'
    # user_list = 'YouXiongKai|YunShaoNianTaiMeiHao|porunacabeza|jinnil|fan'
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s' % (get_token())
    agent_id = '1000002'

    send_values = {
        'touser': userlist,
        'msgtype': 'markdown',
        'agentid': agent_id,
        "markdown":  {
        "content": msg
        }
        # "enable_duplicate_check": 0,
        # "duplicate_check_interval": 1800,
        # 'safe': '0'
    }
    send_msgs = (bytes(json.dumps(send_values), 'utf-8'))
    res = requests.post(send_url, send_msgs).json()   
    
def send_markdown_robot(msg):
#     user_list = 'YouXiongKai'
    # user_list = 'YouXiongKai|YunShaoNianTaiMeiHao|porunacabeza|jinnil|fan'
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=df0a3c77-4311-40cc-80dd-2378b67649c8'
    send_values={
    
    "msgtype": "markdown",
    "markdown": {
    "content": msg
        }

    }
    send_msgs = (bytes(json.dumps(send_values), 'utf-8'))
    res = requests.post(send_url, send_msgs).json()  
    
def send_message_robot():
#     user_list = 'YouXiongKai'
    # user_list = 'YouXiongKai|YunShaoNianTaiMeiHao|porunacabeza|jinnil|fan'
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=df0a3c77-4311-40cc-80dd-2378b67649c8'
    send_values={
    
      "msgtype": "text",
       "text": {
            "content": "我搞了个群聊机器人，哈哈哈哈",
            "mentioned_list":["fan","YouXiongKai"],
        }
    }
    send_msgs = (bytes(json.dumps(send_values), 'utf-8'))
    res = requests.post(send_url, send_msgs).json()
    
    
    
def check_status(port):
    ip = '115.159.202.194'
    status = ''

    try:
        tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp_client.connect((ip, port))
    except Exception as e:
        if port in [25503, 25500]:
            status = 'WARNING: [ABNORMAL] server: %s, port: %d' % (ip, port)
            print(status)
        send_msg(status)
    finally:
        tcp_client.close()

if __name__ == '__main__':
    print('INFO: checking status at')
    check_status(25503)
    check_status(25500)
